﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Silverlight.PreLoading
{
    public class PreLoader : IPreLoadable
    {
        public event EventHandler<PreLoadingProgressEventArgs> OnPreLoadingProgress;
        public string[] Values;
        public event EventHandler<PreLoadingItemCompleteEventArgs> OnPreLoaded;
        public event EventHandler OnPreLoadFailed;
        readonly string _uri;  
        public Stream Stream { get; private set; }
        public string Category { get; private set; }
        private WebClient _client;
        public double Progress { get; private set; }

        public PreLoader(string uriString, string category)
        {
            _uri = uriString;
            Category = category;
        }

        public void PreLoad()
        {
            _client = new WebClient();
            _client.DownloadProgressChanged += ClientDownloadProgressChanged;
            _client.OpenReadCompleted += ClientOpenReadCompleted;
            _client.OpenReadAsync(new Uri(_uri));
        }

        void ClientOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            Stream = e.Result;
            if (OnPreLoaded != null)
                OnPreLoaded(this, new PreLoadingItemCompleteEventArgs() { Item = this });
        }

        void ClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Progress = (double) e.ProgressPercentage/100;
            if (OnPreLoadingProgress != null)
                OnPreLoadingProgress(this, new PreLoadingProgressEventArgs() { Item = this, Message = "Loading...", Progress = (double)e.ProgressPercentage / 100 });
        }
    }
}
